﻿using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic.ClassFactory;
using Common;
using DataAccess;
using Util.PageInfo;
using ValidateCommon;
using System.Globalization;

namespace RichECMS.ServerPages.Section
{
    public partial class RecycleList : Util.BasePage.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                State.strWhereSql = "";
                State.intPageIndex = 1;
                InitDataBind(State.intPageIndex, int.Parse(ddlShowCount.SelectedValue));
                AspNetPagerList.CurrentPageIndex = State.intPageIndex;
            }
        }

        /// <summary>
        /// 绑定
        /// </summary>
        private void InitDataBind(int intCurrentPage, int intPageSize)
        {
            //设置分页条数
            AspNetPagerList.PageSize = intPageSize;
            try
            {
                //绑定文章类型
                DropDownListMainSectionlist.Items.Clear();
                ListItem listitem = new ListItem("--请选择主板块--", "-1");
                DropDownListMainSectionlist.Items.Add(listitem);
                using (SectionsFactory objFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objsection = objFactory.CreatorBySql("intParentID =0  order by intSortNo desc,  dtmInTime desc");
                    if (objsection != null)
                    {
                        for (int i = 0; i < objsection.Count; i++)
                        {
                            listitem = new ListItem(objsection.DataItem.chvSTCName, objsection.DataItem.intSectionID.ToString());
                            DropDownListMainSectionlist.Items.Add(listitem);
                            objsection.SelectRow(i + 1);
                        }
                    }
                }
                using (ArticleFactory objFactory = new ArticleFactory())
                {
                    StringBuilder strWhere = new StringBuilder();
                    BusinessLogic.ClassFactory.ArticleFactory objArticleFactory = new ArticleFactory();
                    BusinessLogic.BusinessRules.Article objArticle = objArticleFactory.NewInstance();

                    int intTotalCounts = 0;

                    SectionsFactory objSectionFactory = new SectionsFactory();
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(State.intSTID);
                    if (intPageSize == 0)
                    {
                        intPageSize = objArticle.GetTotalCount(" intArticleID not in (select distinct intArticleID from ArtSecRelation)");  //显示所有
                    }
                    int intPageFrom = intCurrentPage * intPageSize;

                    if (State.strWhereSql.Trim().Length == 0)
                    {
                        intTotalCounts = objArticle.GetTotalCount(" intArticleID not in (select distinct intArticleID from ArtSecRelation)");
                    }
                    else
                    {
                        intTotalCounts = objArticle.GetTotalCountByCustomSql("SELECT count(*)  from Article" + " where  intArticleID not in (select distinct intArticleID from ArtSecRelation)" + State.strWhereSql);
                    }

                    LitPageCurrent.Text = intCurrentPage.ToString();
                    LitPageCount.Text = intTotalCounts.ToString();
                    if (intTotalCounts % intPageSize != 0)
                    {
                        if ((intCurrentPage == intTotalCounts / intPageSize + 1))
                        {
                            intPageFrom = (intCurrentPage - 1) * intPageSize;
                            intPageSize = intTotalCounts % intPageSize;
                            intPageFrom = intPageFrom + intPageSize;
                        }
                    }

                    strWhere.Append("select * from (select top " + intPageSize + " * from  (select Top " + (intPageFrom).ToString() + " * from (select Top " + (intPageFrom).ToString() + " * from Article " + " where  intArticleID not in (select distinct intArticleID from ArtSecRelation)" + State.strWhereSql + " order by dtmInTime desc,intArticleId desc)t order by  dtmInTime asc ,intArticleId asc)m " + " order by dtmInTime asc ,intArticleId asc)mm  order by dtmInTime desc ,intArticleId desc");

                    BusinessLogic.BusinessRules.Article objArticleList = objArticleFactory.CreatorByFullSql(strWhere.ToString());
                    if (objArticleList != null)
                    {
                        rptList.DataSource = objArticleList.Data.Article.DataSet.Tables[0].DefaultView;
                        AspNetPagerList.RecordCount = intTotalCounts;
                        rptList.DataBind();
                        LitPageTotal.Text = AspNetPagerList.PageCount > 0 ? AspNetPagerList.PageCount.ToString() : "1";
                    }
                    else
                    {
                        rptList.DataSource = objFactory.NewInstance().Data.Article.DataSet.Tables[0].DefaultView;
                        AspNetPagerList.RecordCount = 0;
                        rptList.DataBind();
                        LitPageTotal.Text = AspNetPagerList.PageCount > 0 ? AspNetPagerList.PageCount.ToString() : "1";
                        //Alert("暂无数据！");
                    }
                    objSectionFactory.Dispose();
                }
            }
            catch (Exception ex)
            {
                Alert(ex.ToString().Replace("\r\n", " "));
            }
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImageButtonsearch(object sender, ImageClickEventArgs e)
        {
            StringBuilder sbWhere = new StringBuilder();
            if (txtTitle.Value.Trim() != "")
            {
                sbWhere.AppendFormat(" and chvTitle like '%{0}%'", txtTitle.Value.Trim());
            }
            if (txtDatetime.Value.Trim() != "")
            {
                sbWhere.AppendFormat(" and dtmInTime>#{0}#", Convert.ToDateTime(txtDatetime.Value.Trim()));
            }
            if (txtKey.Value.Trim() != "")
            {
                sbWhere.AppendFormat(" and chvKeyWords like '%{0}%'", txtKey.Value.Trim());
            }
            State.strWhereSql = sbWhere.ToString();
            State.intPageIndex = 1;
            InitDataBind(State.intPageIndex, int.Parse(ddlShowCount.SelectedValue));
        }

        /// <summary>
        /// 删除所选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeleteAll_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                using (DBManager objDBManager = new DBManager())
                {
                    objDBManager.BeginTransaction();
                    try
                    {
                        //文章表
                        ArticleFactory objFactory = new ArticleFactory(objDBManager);
                        objFactory.DeleteArticleWhere(" intArticleId in (" + SortHidden.Value.Trim() + ")");
                        //提交
                        objDBManager.Commit();
                        AlertAndRedirect("信息删除成功", "../Section/RecycleList.aspx", false);
                        objFactory.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Alert(ex.ToString().Replace("\r\n", " "));
                        objDBManager.Rollback();
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Alert(ex.ToString().Replace("\r\n", " "));
            }
        }

        /// <summary>
        /// 分页  PageChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPagerArticle_PageChanged(object sender, EventArgs e)
        {
            State.intPageIndex = AspNetPagerList.CurrentPageIndex;
            InitDataBind(AspNetPagerList.CurrentPageIndex, int.Parse(ddlShowCount.SelectedValue));
        }

        /// <summary>
        /// rptList_ItemCommand  编辑   放入回收站  删除
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                using (DBManager objDBManager = new DBManager())
                {
                    int intArticleId = Convert.ToInt32(e.CommandArgument);
                    objDBManager.BeginTransaction();
                    try
                    {
                        //文章表
                        ArticleFactory objFactory = new ArticleFactory(objDBManager);
                        objFactory.DeleteArticleWhere(" intArticleID =" + intArticleId + "");

                        //提交
                        objDBManager.Commit();
                        AlertAndRedirect("删除成功", "../Section/RecycleList.aspx", false);
                        objFactory.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Alert(ex.ToString().Replace("\r\n", " "));
                        objDBManager.Rollback();
                        return;
                    }
                }
            }
            //放入回收站
            if (e.CommandName == "Recycle")
            {
            }
        }

        /// <summary>
        /// 拾取文章
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSubmitGetArticleSection_Click(object sender, EventArgs e)
        {
            if (ParamAuth.IsNumber(ChangeSecHidden.Value.Trim()))
            {
                int intShangeSec = Convert.ToInt32(ChangeSecHidden.Value.Trim());
                try
                {
                    using (DBManager objDBManager = new DBManager())
                    {
                        objDBManager.BeginTransaction();
                        try
                        {
                            //关联表
                            BusinessLogic.ClassFactory.ArticleFactory objArticleFactory = new ArticleFactory(objDBManager);
                            BusinessLogic.ClassFactory.ArtSecRelationFactory objArtSecRelationFactory = new ArtSecRelationFactory(objDBManager);
                            BusinessLogic.BusinessRules.Article objArticle = objArticleFactory.CreatorBySql(" intArticleId in (" + SortHidden.Value.Trim() + ")");
                            if (objArticle != null)
                            {
                                for (int i = 0; i < objArticle.Count; i++)
                                {
                                    BusinessLogic.BusinessRules.ArtSecRelation objArtSecRelation = objArtSecRelationFactory.NewInstance();
                                    objArtSecRelation.DataItem.intSectionID = intShangeSec;
                                    objArtSecRelation.DataItem.blnIssue = (int)Utility.ArticleState.NoIssue;
                                    objArtSecRelation.DataItem.intArticleID = objArticle.DataItem.intArticleID;
                                    objArtSecRelation.DataItem.intWSID = State.LoginUser.WebSiteID;
                                    //获取默认阅读数
                                    string strdefaultreadcount = System.Configuration.ConfigurationSettings.AppSettings["DefaultReadCount"] ?? "0";
                                    objArtSecRelation.DataItem.intAccessCount = ParamAuth.IsNumber(strdefaultreadcount) ? Convert.ToInt32(strdefaultreadcount) : 0;
                                    objArtSecRelation.DataItem.intSort = 0;
                                    objArtSecRelation.DataItem.dtmIssueTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
                                    objArtSecRelation.DataItem.blnIssue = (int)Utility.ArticleState.NoIssue;
                                    objArtSecRelation.DataItem.blnRefers = (int)Utility.ArticleRefersState.NoRefers;
                                    objArtSecRelation.DataItem.intState = (int)Utility.ArticleState.NoIssue;
                                    objArtSecRelation.DataItem.intType = (int)Utility.ArticleType.Article;
                                    //文章位置状态
                                    objArtSecRelation.DataItem.intVerify = 0;
                                    objArtSecRelation.DataItem.intGlobalRec = 0;
                                    objArtSecRelation.DataItem.intSectionRec = 0;
                                    objArtSecRelation.DataItem.intGlobalTop = 0;
                                    objArtSecRelation.DataItem.intSectionTop = 0;
                                    objArtSecRelation.DataItem.intScroll = 0;
                                    objArtSecRelation.Insert();

                                    objArticle.DataItem.intRecycling = (int)Utility.ArticleState.NoRecycling;
                                    objArticle.Update();

                                    objArticle.SelectRow(i + 1);
                                }
                            }
                            //提交

                            SectionsFactory objSFactory = new SectionsFactory(objDBManager);
                            BusinessLogic.BusinessRules.Sections objSections = objSFactory.Creator(intShangeSec);
                            objSections.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;

                            objSections.Update();

                            BusinessLogic.BusinessRules.Sections objSectionsmain = objSFactory.CreatorBySql(" intParentId=0 ");
                            if (objSectionsmain != null)
                            {
                                for (int i = 0; i < objSectionsmain.Count; i++)
                                {
                                    objSectionsmain.DataItem.intIssueState = (int)Utility.STIssueState.NoIssue;
                                    objSectionsmain.SelectRow(i + 1);
                                }
                                objSectionsmain.Update();
                            }

                            objDBManager.Commit();
                            AlertAndRedirect("所选新闻已经提取到指定板块", "../Section/RecycleList.aspx", false);
                            objSFactory.Dispose();
                            objArtSecRelationFactory.Dispose();
                            objArticleFactory.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Alert(ex.ToString().Replace("\r\n", " "));
                            objDBManager.Rollback();
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Alert(ex.ToString().Replace("\r\n", " "));
                }
            }
            else
            {
                Alert("参数错误");
            }
        }

        //显示条数
        protected void ddlShowCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitDataBind(State.intPageIndex, int.Parse(ddlShowCount.SelectedValue));
        }
    }
}